import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite"; //导入loadEnv
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // console.log(command)  pnpm dev[serve]  pnpm build[build]
  // console.log(mode)  获取开发模式
  // console.log(process.cwd()) 可以获取项目所在的路径
  const env = loadEnv(mode, process.cwd());
  console.log(env); //通过这个函数能拿到环境变量

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    server: {
      /* 代理 */
      proxy: {
        "/api": {
          target: env.VITE_BASE_URL,
          changeOrigin: true,
          rewrite: path => {
            // console.log(path);
            return path.replace(/^\/api/, "");
          },
          /* 使用测试时：axios.get("./api/city").then(res=>{res.data})
              将 /api/city 替换成/city  最终得出target + /city */
        },
        "/map": {
          target: env.VITE_BASE_MAP,
          changeOrigin: true,
          rewrite: (path) => {
            // console.log(path);
            return path.replace(/^\/map/, "")
          },
          /* target + /ip */
        },
      },
    },
  };
});
